<template>
  <div class="tag-tree">
    <a-tree
      checkable
      multiple
      v-model="checkedKeys"
      :auto-expand-parent="autoExpandParent"
      :expanded-keys="expandedKeys"
      :selected-keys="selectedKeys"
      :checked-keys="checkedKeys"
      :tree-data="treeData"
      :checkStrictly="true"
      :replaceFields="{children:'children', title:'title', key:'key'}"
      @expand="onExpand"
      @select="onSelect"
      @check="onCheck"
    />
  </div>
</template>

<script>
import { getAction } from '@/api/manage'
export default {
  name: 'tagTree',
  props: {
    pcode:{
      type:String,
      default:'',
      required:false
    },
  },
  data() {
    return {
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      selectedCodes: [],
      treeData: [],
      url:"/sys/category/loadTreeRoot",
    }
  },
  created() {
    this.loadRoot();
  },
  methods: {
    /**加载一级节点 */
    loadRoot(){
      let param = {
        async: false,
        pcode:!this.pcode?'0':this.pcode,
      }
      getAction(this.url,param).then(res=>{
        if(res.success && res.result){
          let result = res.result
          this.treeData = [...result]
          for (let i = 0; i < result.length; i++) {
            let temp = result[i]
            this.setThisExpandedKeys(temp)
          }
        }else{
          console.log("树一级节点查询结果-else",res)
        }
      })
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.expandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onSelect(selectedKeys, e) {
      console.log('onSelect', selectedKeys, e)
      this.selectedKeys = selectedKeys
      // let codes = e.selectedNodes.map((item)=> {
      //   let code = item.data.props.code
      //   return code
      // })
      // this.selectedCodes = codes
      // this.$emit('selectedKeys', codes)
      this.$emit('selectedKeys', selectedKeys)
    },
    onCheck(checkKeys, e) {
      console.log('onCheck', checkKeys, e)
      // let codes = e.checkedNodes.map((item)=> {
      //   let code = item.data.props.code
      //   return code
      // })
      // console.log('codes', codes)
      // this.$emit('checkedKeys', codes)
      this.$emit('checkedKeys', checkKeys.checked)
    }
  }
}
</script>
<style lang="less" scoped>
// .tag-tree {
//   .ant-tree {
//     border:1px #e8e8e8 solid; 
//     position: relative;
//     padding: 5px 0;
//   }
// }
</style>
